package com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectProblem

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

@Serializable
object SelectProblem

fun NavGraphBuilder.selectProblemDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<SelectProblem> {
        val viewModel: SelectProblemViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsStateWithLifecycle().value

        SelectProblemScreen(
            padding = padding,
            uiState = uiState,
            onBack = navController::popBackStack,
            onGetProblemList = viewModel::getProblemList,
            onFilterProblem = viewModel::filterProblem,
            onSelectProblem = {
                CoroutineScope(Dispatchers.IO).launch {
                    SelectProblemEvent.emit(it)
                    delay(500)
                    withContext(Dispatchers.Main) {
                        navController.popBackStack()
                    }
                }
            }
        )
    }
}

fun NavController.navigateToSelectProblem() {
    navigate(SelectProblem)
}